import { useRequest } from 'ahooks';
import { App, Form, Input, Modal, Spin } from 'antd';
import React, { useMemo } from 'react';
import styles from './styles.module.css';
import { DthesaurusContent } from './dthesaurus-content'
import { useContext } from 'react'
import { useTranslation } from 'react-i18next';
import {domainThesaurusCreate,domainThesaurusUpdate} from '@/client/api/domainThesaurus'
import { apiInterceptors,} from '@/client/api';
interface CreatedomainModelProps {
  open: boolean;
  onCancel: () => void;
  refresh?: () => void;
  type?: 'add' | 'edit';
}

const CreatedomainModel: React.FC<CreatedomainModelProps> = ({
  open,
  onCancel,
  type = 'add',
  refresh
}) => {
  const { t } = useTranslation();
  const { domainRow ,sub,login_name} = useContext(DthesaurusContent)
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const formItems = useMemo(() => {
    const DOMAIN_REGEX = /^[a-zA-Z0-9\u4e00-\u9fa5._-]+$/;

    const baseItems = [
      {
        name: 'name',
        label: '词汇库名词',
        txt: '仅支持中文、英文、数字、下划线（_）、中划线（-）、英文点（.）',
        rules: [{ required: true, message: '词汇库名称不能为空' }, { pattern: DOMAIN_REGEX, message: '词汇库名称格式不正确' }],
        required: true,
      },
      {
        name: 'desc',
        label: '描述',
        rules: [{ required: true, message: '描述不能为空' }],
        required: true,
      }
    ];
    return baseItems;
  }, [t, type]); // 添加 type 作为依赖项

  const { run: createDomain, loading: isSubmitting } = useRequest(
    async (params: any) => {
      if (type === 'edit') {
        return await domainThesaurusUpdate({ ...params, creator: sub?sub:login_name, id: domainRow.id });
      } else {
        return await domainThesaurusCreate({ ...params, creator: sub?sub:login_name });
      }
    },
    {
      manual: true,
      onSuccess: async (res) => {
        const {success,err_msg} = res.data||{}
        if(success){
           if (type === 'edit') {
          message.success('更新成功');
          } else {
            message.success('创建成功');
          }
          await refresh?.();
          onCancel();
        }else{
          message.error(err_msg||'操作失败');
        }
        
      }
    }
  );

  return (
    <Modal
      className={styles['modal-container']}
      title={type === 'edit' ? '编辑领域词库' : '创建领域词库'}
      width={800}
      open={open}
      okButtonProps={{ disabled: isSubmitting }}
      onOk={async () => {
        try {
          const values = await form.validateFields();
          await createDomain(values);
        } catch (error) {
          console.error('Submission error:', error);
        }
      }}
      onCancel={onCancel}

      centered
    >
      <Spin spinning={isSubmitting}>
        <Form form={form} initialValues={domainRow} labelAlign="right" >
          {formItems.map(({ name, label, rules, txt }) => (
            <Form.Item required labelCol={{ span: 3 }} wrapperCol={{ span: 20 }} key={name} name={name} label={label} rules={rules}>
              {name == 'name' ? <Input maxLength={20} placeholder={txt} autoComplete="off" showCount /> : <Input.TextArea maxLength={500} placeholder={txt} rows={5} autoComplete="off" showCount />}
            </Form.Item>
          ))}
        </Form>
      </Spin>
    </Modal>
  );
};

export default CreatedomainModel;

